﻿using Gtkj.CMS.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Gtkj.CMS.Common
{
    public class CBEClientHelper
    {
        public static string TGT;
        public static string ST;

        /// <summary>
        /// CAS服务器验证/认证地址(SSO统一服务器地址)
        /// 内网测试地址http://172.21.120.153:5080/Cas/v1/tickets
        /// </summary>
        public static string ssoServerUrl = "http://cas-center.cares.sh.cn:5080/Cas/v1/tickets";
        /// <summary>
        /// 服务接口验证地址，只有验证该jsp，且返回OK后，才能继续调用其它服务
        /// </summary>
        public static string checkServiceUrl = "http://travele.cares.sh.cn:3080/agentboss/servicecheck.jsp";//内网地址
        //public static string checkServiceUrl = "http://travele.cares.sh.cn:3080/agentboss/servicecheck.jsp"; //外网地址，外部调用时，请用这个地址
        /// <summary>
        /// 统一服务接口，调用不同服务时，传递不同的参数即可
        /// </summary>
        public static string routeServiceUrl = "http://travele.cares.sh.cn:3080/agentboss/servlet/com.servlet.EsbRouteServlet";//内网地址
        //public static string routeServiceUrl = "http://travele.cares.sh.cn:3080/agentboss/servlet/com.servlet.EsbRouteServlet";//外网地址，外部调用时，请用这个地址

        /// <summary>
        /// 企业编号/用户帐号
        /// </summary>
        public static string username = "chufeng66621777/chufeng66621777";

        /// <summary>
        /// 密码
        /// </summary>
        public static string password = "111111";

        public static  HttpWebRequest myWebRequest;
        public static CookieContainer cookies = null;   //同sso交互过程中，要保持cookies


        /// <summary>
        /// 第一步：获得TGT
        /// </summary>
        /// <returns>1:成功获取 0：获取失败</returns>
        public static int GetTGT()
        {
            int result = 0;
            string html = "";
            try
            {
                string paramString = "username=" + username + "&password=" + password;
                html = PostMethod(ssoServerUrl, paramString, null);
                Regex r = new Regex(".*action=\".*/(.*?)\".*");
                string responseHtml = html;
                if (r.IsMatch(responseHtml))
                {
                    TGT = r.Match(responseHtml).Groups[1].Value;
                    result= 1;
                    //this.txtBoxTGT.Text = TGT;
                    //rtxResult.AppendText("TGT:" + TGT + "\r\n");
                }
                else
                {
                    result = 0;
                    //rtxResult.AppendText("TGT:没有获得正确的TGT\r\n");
                }
            }
            catch (WebException ex)
            {
                html = ex.Message + "[AgentBoss]";
            }
            return result;
        }
        /// <summary>
        /// 第2步，通过TGT获得对应的ST，且，通过ST验证service，检测是否已经正确通过了SSO统一验证
        /// </summary>
        public static void GetASTService(){

            string html = "";
            try
            {
                string STUrl = ssoServerUrl + "/" + TGT;
                List<Headers> headersList = new List<Headers>();
                Headers headerItem = new Headers();
                headerItem.Key = "service";
                headerItem.Value = checkServiceUrl;
                headersList.Add(headerItem);

                string paramString = "service=" + checkServiceUrl; //传送任意字符串

                ST = PostMethod(STUrl, paramString, null);
                //this.txtBoxAST.Text = ST;
                //rtxResult.AppendText("ST:" + ST + "\r\n");

                //获得ST后，验证一下SSO是否真正成功
                String ssoCheckURL = checkServiceUrl + "?ticket=" + ST;
                paramString = "ticket=" + ST;
                //html = GetServerResource(ssoCheckURL, paramString, null);
                html = PostMethod(ssoCheckURL, paramString, null);
                //rtxResult.AppendText("检测结果:" + html + "\r\n");
            }
            catch (WebException ex){
                html = ex.Message + "[AgentBoss]";
            }
        }



        public static string PostMethod(string requestURL, string paramString, List<Headers> headersList)
        {
            string pagehtml = "";
            try
            {
                Encoding myEncoding = Encoding.GetEncoding("UTF-8");
                Uri myUri = new Uri(requestURL);

                myWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
                myWebRequest.ContentType = "application/x-www-form-urlencoded";
                myWebRequest.AllowAutoRedirect = true;
                myWebRequest.Method = "POST";
                myWebRequest.Timeout = 30000;
                myWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727";
                if (cookies != null)
                {
                    myWebRequest.CookieContainer = cookies;

                }
                if (headersList != null)
                {
                    try
                    {
                        for (int i = 0; i < headersList.Count; i++)
                        {
                            myWebRequest.Headers.Add(headersList[i].Key, headersList[i].Value);
                        }
                    }
                    catch (Exception ee)
                    {
                        string t = ee.Message;
                    }
                }
                
                //Send request
                if (paramString == null || paramString == "")
                {
                    Stream requestStream = myWebRequest.GetRequestStream();
                    requestStream.Close();
                }
                else
                {
                    byte[] paramBytes = myEncoding.GetBytes(paramString);
                    myWebRequest.ContentLength = paramBytes.Length;
                    Stream requestStream = myWebRequest.GetRequestStream();
                    requestStream.Write(paramBytes, 0, paramBytes.Length);
                    requestStream.Close();
                }

                //Get response
                HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
                StreamReader myStreamReader = new StreamReader(myWebResponse.GetResponseStream(), myEncoding);

                if (cookies == null)
                {
                    cookies = new CookieContainer();
                }
                cookies.Add(myWebResponse.Cookies);

                pagehtml = myStreamReader.ReadToEnd();
                myStreamReader.Close();
            }
            catch (WebException ex)
            {
                if (ex.Message == "无法连接到远程服务器")
                {
                    throw new Exception("无法连接到远程服务器", ex);
                }
                else
                {
                    string retMessage = ex.Message;
                    HttpWebResponse res = (HttpWebResponse)ex.Response;
                    StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
                    pagehtml = sr.ReadToEnd() + "[AgentBoss]";
                    return pagehtml;
                }


            }

            return pagehtml;
        }
    }
}